/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TCPprotocolo;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author emanuellima
 */

/* 
 * Tipos de Mensagens: 0 = Criar Jogo
 *                     1 = Mensagem de Texto
 */
public class Protocol {   
    
    private CreateGameMessage message;
    private TextMessage message2;
    
    public Protocol (CreateGameMessage message, TextMessage message2){
        
        this.message = message;
        this.message2 = message2;
        
    } 
    
    public ByteArrayOutputStream encoderCreateGameMessage(CreateGameMessage message) throws IOException{
        
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        DataOutputStream dataOut = new DataOutputStream(byteOut);
        dataOut.writeByte(message.getType());
        dataOut.writeInt(message.getNumbersOfPlayers());
        
        return byteOut;
    }
    
    public ByteArrayOutputStream encoderTextMessage(TextMessage message2) throws IOException{
        
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        DataOutputStream dataOut = new DataOutputStream(byteOut);
        dataOut.writeByte(message2.getType());
        dataOut.writeChars(message2.getText());
        
        
        return byteOut;
    }
    
    public void sendMessage(ByteArrayOutputStream message, Socket socket) throws IOException{
        
        byte msg [] = message.toByteArray();
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());  
        out.writeInt(msg.length); //Agora sim, o tamanho da mensagem  
        out.write(msg); //Os dados  
        out.flush();
    }
   
}
